package ru.paswd.marketprice.ui.widgets.chart.impl.jjoe64

import android.content.Context
import android.graphics.Paint
import android.util.AttributeSet
import com.jjoe64.graphview.GraphView
import com.jjoe64.graphview.GridLabelRenderer
import com.jjoe64.graphview.helper.DateAsXAxisLabelFormatter
import com.jjoe64.graphview.series.DataPoint
import com.jjoe64.graphview.series.LineGraphSeries
import ru.paswd.marketprice.ui.widgets.chart.PriceHistoryItem
import ru.paswd.marketprice.ui.widgets.chart.PriceHistoryView
import java.text.SimpleDateFormat
import java.util.*

class Jjoe64PriceHistoryView : PriceHistoryView {

    private var graphView: GraphView? = null

    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)

    override fun setItems(items: List<PriceHistoryItem>) {
        if (graphView == null) {
            initGraphView()
        }

        val series = LineGraphSeries<DataPoint>()
        series.color = getPrimaryColor()

        items.forEach { i ->
            series.appendData(
                    DataPoint(i.x, i.y),
                    false, items.size
            )
        }

        val min = Collections.min(items, argumentComparator).x
        val max = Collections.max(items, argumentComparator).x

        series.isDrawDataPoints = true

        graphView?.gridLabelRenderer?.verticalLabelsSecondScaleAlign = Paint.Align.LEFT

        graphView?.removeAllSeries()
        graphView?.addSeries(series)

        graphView?.viewport?.setMinX(min)
        graphView?.viewport?.setMaxX(max)
    }

    private fun initGraphView() {
        graphView = setWidget { GraphView(context) }

        graphView?.gridLabelRenderer?.labelFormatter = DateAsXAxisLabelFormatter(
                context, SimpleDateFormat("dd.MM"))

        graphView?.viewport?.isXAxisBoundsManual = true
        graphView?.gridLabelRenderer?.labelsSpace = 20
        graphView?.gridLabelRenderer?.gridStyle = GridLabelRenderer.GridStyle.VERTICAL
    }
}